package com.nti56.springboot.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.nti56.springboot.utils.Constant;

@WebFilter(filterName = "sessionFilter",urlPatterns = {"/*"})
public class SessionFilter implements Filter {
	
	private static final Logger logger = LoggerFactory.getLogger(SessionFilter.class);
	
	// 标示符：表示当前用户未登录(可根据自己项目需要改为json样式)
	String NO_LOGIN = "您还未登录";

	// 不需要登录就可以访问的路径(比如:注册登录等)
	String[] includeUrls = new String[] {"/login","/loginAuth","/json","/services","/api",".js",".css",".ico",".jpg",".png"};

	@Override
	public void doFilter(ServletRequest servletRequest,
			ServletResponse servletResponse, FilterChain filterChain)
			throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) servletRequest;
		HttpServletResponse response = (HttpServletResponse) servletResponse;
		HttpSession session = request.getSession();		
		String uri = request.getRequestURI();
		// 是否需要过滤
		boolean needFilter = isNeedFilter(uri);
		logger.debug("uri:---"+uri + " needFilter:"+needFilter);
		if (!needFilter) { // 不需要过滤直接传给下一个过滤器
			//filterChain.doFilter(servletRequest, servletResponse);
			this.jumpTabs(request, response, filterChain);
		} else { 
			// 需要过滤器						
			logger.debug("session:---"+session.getAttribute(Constant.SESSION_USER_KEY));
			if(session == null || session.getAttribute(Constant.SESSION_USER_KEY) == null ) {
				String requestType = request.getHeader("X-Requested-With");
				// 判断是否是ajax请求
				logger.debug("requestType:---"+requestType);
				if (requestType != null && requestType.equalsIgnoreCase("XMLHttpRequest")) {
					//response.getWriter().write(this.NO_LOGIN);
					response.setHeader("sessionstatus", "timeout");
					response.getWriter().print("登录超时！");
				} else {
					// 重定向到登录页(需要在static文件夹下建立此html文件)
					response.sendRedirect(request.getContextPath()+ "/system/login");
				}
				return;
			}else {
				filterChain.doFilter(request, response);
			}
			
		}
	}
	
	/**
	 * 当session超时时候，springboot内置tomcat可以正常请求URL，
	 * 而部署的tomcat请求的url是 login,但是requestType ='XMLHttpRequest'
	 * eclipse开发是没有此问题，但是部署到单独的tomcat会有此问题，所以修改为下面这个方法
	 * 解决部署到 tomcat后，session为空，点击Ajax请求，无法跳出ifram问题
	 * @param request
	 */
	private void jumpTabs(HttpServletRequest request,HttpServletResponse response,
			FilterChain filterChain) throws IOException, ServletException {
		String requestType = request.getHeader("X-Requested-With");
		String uri = request.getRequestURI();
		if (requestType != null 
				&& requestType.equalsIgnoreCase("XMLHttpRequest")
				&& uri.indexOf("login") != -1) {
			response.setHeader("sessionstatus", "timeout");
		}else {
			filterChain.doFilter(request, response);
		}
	}
	
	/**
	 * @Author: xxxxx
	 * @Description: 是否需要过滤
	 * @Date: 2018-03-12 13:20:54
	 * @param uri
	 */
	public boolean isNeedFilter(String uri) {		
		for (String includeUrl : includeUrls) {
			if (uri.indexOf(includeUrl) != -1) {
				return false;
			}
		}
		return true;
	}
	
	
	
	@Override
	public void init(FilterConfig filterConfig) throws ServletException {

	}

	@Override
	public void destroy() {

	}

}
